#pragma once
#include <iostream>
#include <string>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<time.h>
#include<stdio.h>
#include<cstdarg>
#define LogFile "log.txt"

enum
{
    Screen = 1,
    OneFile,
    ClassFile
};

enum
{
    Info = 0,
    Debug,
    Warning,
    Error,
    Fatal
};

class Log
{
public:
    Log()
    {
        printmethod = Screen;
        path = "./log/";
    }
    void Enable(int method)
    {
        printmethod = method;
    }

    std::string levelToString(int level)
    {
        switch (level)
        {
        case Info:
            return "Info";
        case Debug:
            return "Debug";
        case Warning:
            return "Warning";
        case Error:
            return "Error";
        case Fatal:
            return "Fatal";
        default:
            return "None";
        }
    }

    void PrintLog(int level,const std::string&logtxt)
    {
        switch (printmethod)
        {
        case Screen:
            PrintScreen(logtxt);
            break;
        case OneFile:
            PrintOneFile(LogFile,logtxt);
            break;
        case ClassFile:
            PrintfClassFile(level,logtxt);
            break;
        default:
            break;
        }
    }
    void PrintScreen(const std::string&logtxt)
    {
        std::cout<<logtxt<<std::endl;
    }

    void PrintOneFile(const std::string& filename,const std::string&logtxt)
    {
        std::string _filename=path+filename;
        int fd=open(_filename.c_str(),O_WRONLY|O_CREAT|O_TRUNC,0664);
        if(fd<0)
        {
            perror("open");
            return;
        }
        char buffer[1024];
        write(fd,logtxt.c_str(),logtxt.size());
        close(fd);
    }
    void PrintfClassFile(int level,const std::string&logtxt)
    {   
        std::string filename=LogFile;
        filename+=".";
        filename+=std::to_string(level);
        PrintOneFile(filename,logtxt);
    }

    void operator()(int level,const char*format,...)
    {
        //时间获取与格式化
        time_t tm=time(nullptr);
        struct tm*ctime=localtime(&tm);
        char leftbuffer[1024];
        snprintf(leftbuffer,sizeof(leftbuffer),"[%s][%d-%d-%d-%d-%d-%d]",levelToString(level).c_str(),ctime->tm_year+1900,
                ctime->tm_mon+1,ctime->tm_mday,ctime->tm_hour,ctime->tm_sec);
        va_list s;
        va_start(s,format);
        char rightBuffer[1024];
        vsnprintf(rightBuffer,sizeof(rightBuffer),format,s);
        va_end(s);
        //格式：默认部分+自定义部分
        char logtxt[11024*2];
        snprintf(logtxt,sizeof(logtxt),"%s %s\n",leftbuffer,rightBuffer);
        PrintScreen(logtxt);
    }

    ~Log()
    {
    }

private:
    int printmethod;
    std::string path;
};